package com.leyou.search.listeners;

import com.leyou.search.service.IndexService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.leyou.common.constants.MQConstants.Exchange.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.Queue.SEARCH_ITEM_DOWN;
import static com.leyou.common.constants.MQConstants.Queue.SEARCH_ITEM_UP;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_UP_KEY;


@Component
public class Listener {

    @Autowired
    private IndexService indexService;

    /**
     * 使用注解的方式，完成绑定，队列和交换机的绑定
     *  @QueueBinding 声明绑定
     *  @Queue 声明队列 durable，支持持久化
     *  @Exchange 声明交换机
     *  ignoreDeclarationExceptions 忽略声明异常，
     *  MQ消息确认机制，默认是自动确认，spring整合后变成了手动确认，但是没有确认代码
     *  和异常绑定起来，没有异常，就确认，有异常就不确认
     * key routingkey声明 #.# 可接纳所有内容
     *
     * 接收方法，接收的数据类型，一定要和发送方的数据类型一致
     * @param spuId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = SEARCH_ITEM_UP, durable = "true"),
            exchange = @Exchange(
                    value = ITEM_EXCHANGE_NAME,
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC
            ),
            key = {ITEM_UP_KEY}))
    public void listenUp(Long spuId){

        this.indexService.createIndexes(spuId);
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = SEARCH_ITEM_DOWN, durable = "true"),
            exchange = @Exchange(
                    value = ITEM_EXCHANGE_NAME,
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC
            ),
            key = {ITEM_DOWN_KEY}))
    public void listenDown(Long  spuId){

        this.indexService.deleteIndexes(spuId);
    }
}
